package com.example.noobpackage.logic.repository

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.liveData
import com.example.noobpackage.logic.model.AcceptedPackage
import com.example.noobpackage.logic.model.ExpressData
import com.example.noobpackage.logic.model.MarketPackageData
import com.example.noobpackage.logic.network.MarketPackageService
import com.example.noobpackage.logic.network.OnlineExpressService
import com.example.noobpackage.logic.network.ServiceCreator
import kotlinx.coroutines.Dispatchers

object MarketRepository {
    // 代取市场仓库层
    private val marketPackageService = ServiceCreator.create<MarketPackageService>()
    private val packagesList = MutableLiveData<List<MarketPackageData>>()

    private val onlineExpressService = ServiceCreator.create<OnlineExpressService>()
    private val _acceptedPackage = MutableLiveData<List<AcceptedPackage>>()
    val acceptedPackage: LiveData<List<AcceptedPackage>>
        get() {
            return _acceptedPackage
        }

    fun getMarketPackages(): LiveData<List<MarketPackageData>> {
        return packagesList
    }

    suspend fun updateMarketPackages(account: Long) {
        try {
            Log.d("AppNetwork", "load marketPackages")
            val response = marketPackageService.loadMarketPackages(account)
            Log.d("AppNetwork", "load marketPackages success $response")
            packagesList.postValue(response)
        } catch (e: Throwable) {
            Log.d("AppNetwork", "load marketPackages failed")
            e.printStackTrace()
        }
    }

    fun getPackage(position: Int): MarketPackageData? {
        return packagesList.value?.get(position)
    }

    fun acceptMarketPackage(id: String, account: Long) = liveData(Dispatchers.IO) {
        var acceptRes = marketPackageService.acceptMarketPackage(id, account)
        emit(acceptRes)
    }

    suspend fun updateAcceptedPackages(account: Long) {
        try {
            Log.d("AppNetwork", "load acceptedPackages")
            val response = onlineExpressService.loadAcceptedPackage(account)
            Log.d("AppNetwork", "load acceptedPackages success")
            _acceptedPackage.postValue(response)
        } catch (e: Throwable) {
            Log.d("AppNetwork", "load acceptedPackages failed")
            e.printStackTrace()
        }
    }

}
